/*
 * @Author: HZK
 * @Date: 2020-09-16 09:52:01
 * @LastEditTime: 2020-12-29 13:55:25
 * @LastEditors: hanfengmi
 * @Description: 工作使用的js辅助方法集合
 * 
 */
import {
  parse
} from 'qs'

/* 打乱数组 */
export const arrayShuffle = array => {
  if (!Array.isArray(array)) {
    throw new Error('Argument must be an array')
  }
  let end = array.length
  if (!end) {
    return array
  }
  while (end) {
    let start = Math.floor(Math.random() * end--);
    [array[start], array[end]] = [array[end], array[start]]
  }
  return array
}

/* 判断是否是url */
export const isUrl = str => /^(((ht|f)tps?):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?$/.test(str)

export const isBase64 = str => /^data:image/.test(str)

/* 获取指定范围随机数 */
export const getRandom = (min = 0, max = 100) => {
  if (typeof min !== 'number' || typeof max !== 'number') {
    throw new Error('Argument(s) is illegal !')
  }
  if (min > max) {
    [min, max] = [max, min]
  }
  return Math.floor(Math.random() * (max - min + 1) + min)
}

// console.log(getRandom(1, 20)) // 89

/* 文件尺寸格式化 */
export const formatSize = size => {
  if (typeof + size !== 'number') {
    throw new Error('Argument(s) is illegal !')
  }
  const unitsHash = 'B,KB,MB,GB'.split(',')
  let index = 0
  while (size > 1024 && index < unitsHash.length) {
    size /= 1024
    index++
  }
  return Math.round(size * 100) / 100 + unitsHash[index]
}

//formatSize('10240') // 10KB    formatSize('10240000') // 9.77MB

/* 缩减文件名 ex: 什么时候去吃麦当劳.txt => 什么时...麦当劳.txt */
export const minName = name => {
  if (name.length && name.length > 12) {
    const [name_, type] = name.split('.')
    return `${name_.slice(0,3)}...${name_.slice(name_.length - 3)}.${type}`
  }
  if (name.length && name.length <= 12) {
    return name
  }
  return null
}

/* 获取url中key */ 
export const getUrlKey = (key) => { 
  if(key === 'ciId') {
    return parse(window.location.href.split('?')[1]).ciId || 'F534DB71F1F5DA2D'
  }
  return parse(window.location.href.split('?')[1])[key]
}

/* 格式化数字 */
export const formatNum = (num, point = 1) => {
  if (num >= 0) {
    let numStr = num.toString().split('.')[0]
    if (numStr.length < 5) { // 判断数字有多长,如果小于6,,表示10万以内的数字,让其直接显示
      return numStr
    } else if (numStr.length >= 5 && numStr.length <= 8) { // 如果数字大于6位,小于8位,让其数字后面加单位万
      let decimal = numStr.substring(numStr.length - 4, numStr.length - 4 + point)
      // 由千位,百位组成的一个数字
      return parseFloat(parseInt(num / 10000) + '.' + decimal) + '万'
    } else if (numStr.length > 8) { // 如果数字大于8位,让其数字后面加单位亿
      let decimal = numStr.substring(numStr.length - 8, numStr.length - 8 + point)
      return parseFloat(parseInt(num / 100000000) + '.' + decimal) + '亿'
    }
  }
  return 'error'
}

/* 上传文件格式限制 */
export const acceptFileType = `
  image/png, 
  image/jpg, 
  image/jpeg,
  application/msword,
  application/vnd.openxmlformats-officedocument.wordprocessingml.document,

  application/vnd.ms-powerpoint,
  application/vnd.openxmlformats-officedocument.presentationml.presentation,

  text/plain,

  application/vnd.ms-excel,
  application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
  
  .zip,
  .rar,
  application/x-rar-compressed,
  application/zip,
  application/x-zip-compressed
`

/* 下载文件 */ 
export const downloadFile = (url = '', name = 'undefined') => {
  const origin = window.location.origin
  window.open(`${origin}/ArticleService/article/index.php?r=Article/downLoadFile&data=${JSON.stringify({file_url: encodeURIComponent(url), file_name:name})}`, '_blank')
}

/* 统一登录登出 */
export const loginOut = type => {
  localStorage.removeItem('fwq-auth-token')
  localStorage.removeItem('fwq-user-info')
  const origin = window.location.origin
  if (type === 'login') {
    // alert(`${origin}/SSOService/sso/index.php?r=Yhtsignin/RedirectLogin&yht_jump_type=2&ciId=${getCiId()}`)
    window.open(`${origin}/SSOService/sso/index.php?r=Yhtsignin/RedirectLogin&yht_jump_type=2&ciId=${getUrlKey('ciId')}`, '_self')
  } else {
    localStorage.clear()
    window.open(`${origin}/up_service/index.php?r=public/logout&yht_jump_type=2&ciId=${getUrlKey('ciId')}`, '_self')
  }
}